#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# Author:    LJ
# Email:     admin@attacker.club
# Date:      18-3-27
# Description:
"""

import re
import os
import re
import sys
import shlex
import time
import argparse
import platform
import logging
import subprocess
import logging
from logging.handlers import RotatingFileHandler
import subprocess
import json
try:
    import configparser
except:
    import ConfigParser as configparser

# yum install python-pip


def bash(cmd):
    """
    执行执行bash命令
    """
    return shlex.os.system(cmd)


def shell(cmd):
    """ shell执行  """
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    results = p.communicate()[0]
    return results.decode()


def run_shell(cmd):
    """
    执行系统命令
    """
    (status, output) = subprocess.getstatusoutput(cmd)
    context = {
        'status': status,
        'output': output,
    }
    return context


def file_io(path, method, content):
    """ 文件写入  """
    with open(path, method) as f:
        f.write(content)


def found_ip(content):
    """ 提取包含的ip,生成列表 """
    iplist = re.findall(
        r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", content)
    if iplist:
        return iplist


class LoggerLog:
    def __init__(self, name=__name__):
        """
        实例化LoggerFactory类时的构造函数
        :param name:
        """
        # 实例化logging
        self.logger = logging.getLogger(name)
        # 输出的日志格式
        self.formatter = formatter = logging.Formatter(
            '%(asctime)s %(name)s: %(levelname)s %(message)s')

    def create_logger(self):
        """
        构造一个日志对象
        """
        # 设置日志级别
        self.logger.setLevel(logging.DEBUG)
        # 设置日志输出的文件
        os.makedirs('logs', exist_ok=True)
        handle = logging.FileHandler('./logs/scripts.log')
        # 输出到日志文件的日志级别
        handle.setLevel(logging.INFO)
        handle.setFormatter(self.formatter)
        self.logger.addHandler(handle)
        # 输出到控制台的显示信息
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(self.formatter)
        self.logger.addHandler(console)


def parse_args():

    parser = argparse.ArgumentParser(
        usage="lazy tools",
        description="懒人命令集: 整合常用命令行语句 ^_^ ",
        add_help=False,
        formatter_class=lambda prog: argparse.RawTextHelpFormatter(
            prog, max_help_position=50)
    )
    parser.add_argument("--help",
                        action="help",
                        help="查看帮助信息")

    parser.add_argument("-L", "--log",
                        default="info",
                        help="设置LOG级别")

    parser.add_argument("--uninstall",   
                        action="store_true",
                        help="卸载")

    parser.add_argument("-n", "--name",
                        help="任务名称")

    parser.add_argument('-t', '--type',
                        # required=True,  # (必备参数)
                        help="类型, git自动提交；")

    parser.add_argument('-P', '--port',
                        type=int,
                        default=8000,
                        help='服务器端口，默认为8000')
    parser.add_argument('-u', '--user',
                        help='用户')
    parser.add_argument('-p', '--passwd',
                        help='密码')
    parser.add_argument('--url',
                        default="http://127.0.0.1:8000",
                        help='请求页面')

    parser.add_argument('-h', '--host',
                        default='0.0.0.0',
                        help='服务器IP，默认为0.0.0.0')

    parser.add_argument('-s', '--source', nargs='*', help="源地址目录,可输入多个")
    parser.add_argument('-c', '--config',
                        help="读取脚本同名的配置文件: ",
                        )
    parser.add_argument('-o', '--output',
                        help='输出文件名称')

    args = parser.parse_args()
    # print("打印所有变量",vars(args))
    return args


def req(args):
    if args.type == "token":
        # print(args.user, args.passwd)
        print("token认证")
    return args.url


def print_json(data):
    data = data
    ret = json.dumps(data)
    return ret


if __name__ == '__main__':
    now = time.time()
    start_time = time.strftime("%Y%m%d%H%M", time.localtime(now))
    version = '1.0.0'
    if len(sys.argv) == 1:
        """ 如果没有参数则查看帮助信息 """
        sys.argv.append("--help")
        args = parse_args()

    args = parse_args()
    req(args)

    if args.uninstall:
      print("卸载")
      exit(1)
    else:
      print("执行中")



    res = run_shell("sleep 3")  # 执行shell
    end_time = time.strftime("%Y%m%d%H%M", time.localtime(now))

    data = [{'jobname': args.name, 'start_time': start_time,
             'end_time': end_time, 'result': res['status'], 'post': args.url}]
    ret = print_json(data)
    print(ret)

    # Log = LoggerLog("demo")
    # Log.create_logger()
    # Log.logger.info('这是测试INFO输出')
    # # debug,warning,error

    # s = shell('curl -s ifconfig.io')
    # Log.logger.info(s)
    # print(s, type(s))
    # file_io('logs/file.txt', 'w', s)
